<template>
  <div>
    <el-form
      ref="deptForm"
      :model="form"
      label-width="120px"
      :rules="deptFormRules"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="form.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="form.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="form.manager"
          style="width: 80%"
          placeholder="请选择"
        >
          <el-option
            v-for="ele in list"
            :key="ele.id"
            :value="ele.username"
            :label="ele.username"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="form.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
        <el-button size="small" @click="hCancel">取消</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import {
  addDepartments,
  getDepartDetail,
  updateDepartments
} from '@/api/department'
import { getEmployeeSimple } from '@/api/employee'
export default {
  props: {
    pid: {
      required: true,
      type: String
    },
    isEdit: {
      required: true,
      type: Boolean
    },
    // 业务校验需要的数组
    validList: {
      required: true,
      type: Array
    }
  },
  data() {
    const validCode = (rule, value, callback) => {
      let newValidList = this.validList
      if (this.isEdit) {
        // 如果是编辑状态 当前的code可以直接从form里面拿到 把这一项排除出去
        newValidList = this.validList.filter(
          (ele) => ele.code !== this.form.code
        )
      }
      if (newValidList.find((ele) => ele.code === value)) {
        callback(new Error(value + ':部门编码不能重复'))
      } else {
        callback()
      }
    }
    const validName = (rule, value, callback) => {
      // 过滤出当前点击部门的子部门的名字
      let validNameList = this.validList
        .filter((ele) => ele.pid === this.pid)
        .map((item) => item.name)
      // console.log(validNameList)
      // 编辑状态校验数组 = 当前点击的部门的兄弟部门 - 当前点击的部门
      if (this.isEdit) {
        // 编辑状态需要用到的校验数组
        validNameList = this.validList
          .filter((ele) => ele.pid === this.form.pid && ele.id !== this.pid)
          .map((item) => item.name)
      }
      if (validNameList.includes(value)) {
        callback(new Error(value + ':部门名称不能重复'))
      } else {
        callback()
      }
    }
    return {
      list: [],
      form: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      deptFormRules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称为1-50个字符', trigger: 'blur' },
          { validator: validName, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码为1-50个字符', trigger: 'blur' },
          { validator: validCode, trigger: 'blur' }
        ], // 部门编码
        manager: [
          { required: true, message: '部门管理者必填', trigger: 'blur' }
        ], // 部门管理者
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          { min: 1, max: 300, message: '部部门介绍1-50个字符', trigger: 'blur' }
        ] // 部门介绍
      }
    }
  },
  // watch: {
  //   // 监听pid变化
  //   pid: function() {
  //     this.initDepartDetail()
  //   }
  // },
  created() {
    this.initSimpleList()
    if (this.isEdit) this.initDepartDetail()
  },
  methods: {
    // 清空表单
    resetFrom() {
      // el-form提供的resetFields()方法可以重置表单和表单校验结果
      this.$refs.deptForm.resetFields()
    },
    // 新增
    async doAdd() {
      try {
        // 补参数 pid由父组件传入
        const data = { ...this.form, pid: this.pid }
        const res = await addDepartments(data)
        this.$message.success(res.message)
      } catch (err) {
        console.log(err)
      }
      // console.log(res)
      this.$emit('success')
    },
    // select下拉列表
    async initSimpleList() {
      try {
        const res = await getEmployeeSimple()
        this.list = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 获取部门详情 数据回填
    async initDepartDetail() {
      try {
        const res = await getDepartDetail(this.pid)
        console.log(res)
        this.form = res.data
      } catch (err) {
        console.log(err)
      }
    },
    // 修改部门详情
    async doEdit() {
      try {
        const res = await updateDepartments(this.form)
        console.log(res)
        this.$emit('success')
      } catch (err) {
        console.log(err)
      }
    },
    // 点击确认按钮 新增
    hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    hCancel() {
      this.$emit('close')
    }
  }
}
</script>
